<script setup lang="ts">
import { ref, watch } from "vue";
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

// 座位类型定义
interface Seat {
  row: string;
  col: number;
  isAvailable: boolean;
  isSelected: boolean;
}

// 从路由参数获取电影和场次数据
const route = useRoute();
const router = useRouter();

const movieData = ref({
  movieId: route.query.movieId,
  movieName: route.query.movieName,
  moviePoster: route.query.moviePoster,
  score: route.query.score,
  duration: route.query.duration,
  type: route.query.type,
  actors: route.query.actors,
  scheduleId: route.query.scheduleId,
  time: route.query.time,
  hall: route.query.hall,
  price: route.query.price,
});

// 初始化座位数据 - 所有座位初始都为可选
const seats = ref<Seat[]>([]);
const rows = ["A", "B", "C", "D", "E"];

// 初始化座位数据
for (let i = 0; i < rows.length; i++) {
  for (let j = 1; j <= 12; j++) {
    seats.value.push({
      row: rows[i],
      col: j,
      isAvailable: true, // 初始全部可选
      isSelected: false,
    });
  }
}

// 存储已选座位
const selectedSeats = ref<Seat[]>([]);

// 获取Redis中的座位状态
const fetchSeatStatusFromRedis = async () => {
  try {
    // 构建Redis键名格式：seat:{scheduleId}:{coordinate}
    const scheduleId = movieData.value.scheduleId;

    // 遍历所有座位，检查Redis中对应座位的状态
    for (const seat of seats.value) {
      const redisKey = `${scheduleId}/${seat.row}${seat.col}`;

      // 调用API查询Redis状态
      const response = await axios.get(
        `http://localhost:8080/app/seat-status/${redisKey}`
      );
      console.log("Redis状态:", response);

      if (
        response.data.data &&
        (response.data.data === 1 || response.data.data === 2)
      ) {
        // 如果Redis中值为1或2，则该座位不可选
        seat.isAvailable = false;
      }
    }
  } catch (error) {
    console.error("获取Redis座位状态失败:", error);
  }
};

// 在组件挂载后获取Redis座位状态
onMounted(async () => {
  await fetchSeatStatusFromRedis();
});

// 选择座位
const selectSeat = (seat: Seat) => {
  // 如果座位不可选，直接返回
  if (!seat.isAvailable) {
    return;
  }

  // 检查是否已经选中
  const index = selectedSeats.value.findIndex(
    (s) => s.row === seat.row && s.col === seat.col
  );

  if (index === -1) {
    // 添加到已选座位列表
    selectedSeats.value.push(seat);
    seat.isSelected = true;
  } else {
    // 从已选座位列表移除
    selectedSeats.value.splice(index, 1);
    seat.isSelected = false;
  }
};

// 计算总价
const getTotalPrice = () => {
  const price = Number(movieData.value.price) || 0;
  return selectedSeats.value.length * price;
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 跳转到支付页面
const goToPayment = () => {
  if (selectedSeats.value.length === 0) {
    alert("请选择至少一个座位");
    return;
  }

  router.push({
    path: "/payment",
    query: {
      orderData: JSON.stringify({
        ...movieData.value,
        selectedSeats: selectedSeats.value,
        totalPrice: getTotalPrice(),
        scheduleId: Number(movieData.value.scheduleId),
      }),
    },
  });
};
</script>

<template>
  <div class="seat-selection-page">
    <!-- 进度条 -->
    <div class="progress-bar">
      <div class="progress-content">
        <div class="progress-step active">1</div>
        <div class="progress-line active"></div>
        <span class="progress-text active">选座</span>
        <div class="progress-line"></div>
        <div class="progress-step">2</div>
        <div class="progress-line"></div>
        <span class="progress-text">支付</span>
      </div>
    </div>

    <!-- 电影信息 -->
    <div class="movie-info">
      <h3>{{ movieData.movieName }}</h3>
      <p>
        星光国际影城（北京朝阳店） | {{ movieData.hall }} | {{ movieData.time }}
      </p>
    </div>

    <div class="seat-order-container">
      <!-- 座位区域 -->
      <div class="seats-area">
        <!-- 银幕 -->
        <div class="screen">银幕</div>

        <!-- 座位网格 -->
        <div class="seats-grid">
          <div
            v-for="seat in seats"
            :key="seat.row + seat.col"
            :class="{
              seat: true,
              available: seat.isAvailable && !seat.isSelected,
              selected: seat.isSelected,
              unavailable: !seat.isAvailable,
            }"
            @click="selectSeat(seat)"
          >
            {{ seat.row }}{{ seat.col }}
          </div>
        </div>

        <!-- 座位说明 -->
        <div class="seat-legend">
          <div class="legend-item">
            <div class="legend-icon available-icon"></div>
            <span class="legend-text">可选座位</span>
          </div>
          <div class="legend-item">
            <div class="legend-icon selected-icon"></div>
            <span class="legend-text">已选座位</span>
          </div>
          <div class="legend-item">
            <div class="legend-icon unavailable-icon"></div>
            <span class="legend-text">已售座位</span>
          </div>
        </div>
      </div>

      <!-- 订单信息 -->
      <div class="order-summary">
        <h3>订单信息</h3>

        <div class="order-detail">
          <p>电影：{{ movieData.movieName }}</p>
          <p>场次：{{ movieData.time }}</p>
          <p>影厅：{{ movieData.hall }}</p>
          <p>票价：¥{{ movieData.price }}/张</p>
        </div>

        <div class="selected-seats">
          <h4>已选座位：</h4>
          <div v-if="selectedSeats.length === 0" class="no-seats">
            请选择座位
          </div>
          <div v-else class="seats-tags">
            <span
              v-for="(seat, index) in selectedSeats"
              :key="index"
              class="seat-tag"
            >
              {{ seat.row }}{{ seat.col }}
            </span>
          </div>
        </div>

        <div class="total-price">
          <p>
            <span>总价：</span>
            <span class="price-value">¥{{ getTotalPrice() }}</span>
          </p>
        </div>

        <div class="button-group">
          <button @click="goBack" class="back-btn">返回</button>
          <button @click="goToPayment" class="confirm-btn">确认选座</button>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
.seat-selection-page {
  padding: 20px;
  width: 1200px;
}

/* 进度条样式 */
.progress-bar {
  margin-bottom: 30px;
}

.progress-content {
  display: flex;
  align-items: center;
  max-width: 500px;
  margin: 0 auto;
}

.progress-step {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background-color: #ddd;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.progress-step.active {
  background-color: #a2131d;
  color: white;
}

.progress-line {
  flex: 1;
  height: 2px;
  background-color: #ddd;
  margin: 0 10px;
}

.progress-line.active {
  background-color: #a2131d;
}

.progress-text {
  color: #999;
}

.progress-text.active {
  color: #a2131d;
  font-weight: bold;
}

/* 电影信息样式 */
.movie-info {
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.movie-info h3 {
  margin-bottom: 10px;
  color: #333;
}

.movie-info p {
  margin: 5px 0;
  font-size: 14px;
}

/* 座位和订单容器 */
.seat-order-container {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

/* 座位区域样式 */
.seats-area {
  flex: 1;
  min-width: 400px;
}

.screen {
  width: 80%;
  height: 30px;
  background-color: #eee;
  margin: 0 auto 30px;
  border-radius: 15px / 5px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #666;
  font-size: 14px;
}

.seats-grid {
  display: grid;
  grid-template-columns: repeat(12, 40px);
  gap: 8px;
  justify-content: center;
}

.seat {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  cursor: pointer;
}

.seat.available {
  background-color: white;
  color: #333;
  border: 1px solid #ccc;
}

.seat.selected {
  background-color: #a2131d;
  color: white;
  border: none;
}

.seat.unavailable {
  background-color: #ccc;
  color: #999;
  border: none;
}

/* 座位说明样式 */
.seat-legend {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.legend-icon {
  width: 20px;
  height: 20px;
}

.available-icon {
  border: 1px solid #ccc;
  background-color: white;
}

.selected-icon {
  background-color: #a2131d;
}

.unavailable-icon {
  background-color: #ccc;
}

.legend-text {
  font-size: 14px;
}

/* 订单信息样式 */
.order-summary {
  flex: 0 0 300px;
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 20px;
  height: fit-content;
}

.order-summary h3 {
  margin-bottom: 20px;
  color: #333;
  font-size: 18px;
}

.order-detail {
  margin-bottom: 15px;
}

.order-detail p {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.selected-seats {
  margin: 20px 0;
  padding: 10px 0;
  border-top: 1px dashed #eee;
  border-bottom: 1px dashed #eee;
}

.selected-seats h4 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.no-seats {
  color: #999;
  font-size: 14px;
}

.seats-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.seat-tag {
  background-color: #f0f0f0;
  padding: 3px 8px;
  border-radius: 3px;
  font-size: 13px;
}

.total-price {
  margin: 15px 0;
}

.total-price p {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.price-value {
  color: #a2131d;
  font-weight: bold;
  font-size: 16px;
}

/* 按钮样式 */
.button-group {
  display: flex;
  gap: 10px;
  margin-top: 30px;
}

.back-btn {
  flex: 1;
  padding: 10px 0;
  background-color: white;
  border: 1px solid #ccc;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-btn {
  flex: 1;
  padding: 10px 0;
  background-color: #a2131d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
</style>
